from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from Utils.dss.Serializer import serializer

from Core import models
from Apis.response import Response
from Apis import auth

import json


@csrf_exempt
def index(request):
    res = Response()
    res.output['url'] = request.path
    return res.ok("Hello World")


@csrf_exempt  # csrf 豁免
def list(request):
    response = Response()
    if request.method == 'POST':
        input_array = {
            "session_id": "",
            "account_id": ""
        }
        if len(request.body) == 0:
            return response.error("NullRequest")
        input_array = json.loads(request.body.decode('utf-8'))

        try:
            auth.session_verify_id_s(input_array['session_id'], request.session)
        except Exception as e:
            return response.error("PermissionDeny", e)

        account = models.Account()
        try:
            account = models.Account.objects.get(id=input_array['account_id'])
        except account.DoesNotExist as e:
            return response.error("DoesNotExist", "account [{}] does not exist.".format(input_array['account_id']))

        response.output['account_id'] = input_array['account_id']
        response.output['extra'] = serializer(account.extra_info)
        return response.ok('get accounts extra info success!')
    else:
        return response.error("PostOnly")


@csrf_exempt
def add(request):
    response = Response()
    if request.method == 'POST':
        input_array = {
            "session_id": "",
            "account_id": "",
            "name": "",
            "value": "",
        }
        if len(request.body) == 0:
            return response.error("NullRequest")
        input_array = json.loads(request.body.decode('utf-8'))
        try:
            auth.session_verify_id_s(input_array['session_id'], request.session)
        except Exception as e:
            return response.error("PermissionDeny", e)

        account = models.Account()
        try:
            extra_info = models.AccountExtraInfo()
            extra_info.name = input_array.get('name', '')
            extra_info.value = input_array.get('value', '')
            extra_info.save()

            account = models.Account.objects.get(id=input_array['account_id'])
            account.extra_info.add(extra_info)
            account.save()
        except account.DoesNotExist as e:
            return response.error("DoesNotExist", "account [{}] does not exist.".format(input_array['account_id']))
        except Exception as e:
            return response.error(str(e), "add account extra info failed.")
        response.output['account_info'] = serializer(account, many=True)
        return response.ok("add account extra info success!")
    else:
        return response.error("PostOnly")


@csrf_exempt
def update(request):
    response = Response()
    if request.method == 'POST':
        input_array = {
            "session_id": "",
            "extra_id": "",
            "name": "",
            "value": ""
        }
        if len(request.body) == 0:
            return response.error("NullRequest")
        input_array = json.loads(request.body.decode('utf-8'))
        try:
            auth.session_verify_id_s(input_array['session_id'], request.session)
        except Exception as e:
            return response.error("PermissionDeny", e)

        extra = models.AccountExtraInfo()
        try:
            extra = models.AccountExtraInfo.objects.get(id=input_array['extra_id'])
            extra.name = input_array.get('name', '')
            extra.value = input_array.get('value', '')
            extra.save()
        except extra.DoesNotExist as e:
            return response.error('DoesNotExist',
                                  "account extra info id [{}] not exist.".format(input_array['extra_id']))
        except Exception as e:
            return response.error(str(e), "update account extra info failed.")
        return response.ok("update account extra info [{}] success!".format(input_array['extra_id']))
    else:
        return response.error("PostOnly")


@csrf_exempt
def delete(request):
    response = Response()
    if request.method == 'POST':
        input_array = {
            "session_id": "",
            "extra_id": "",
        }
        if len(request.body) == 0:
            return response.error("NullRequest")
        input_array = json.loads(request.body.decode('utf-8'))
        try:
            auth.session_verify_id_s(input_array['session_id'], request.session)
        except Exception as e:
            return response.error("PermissionDeny", e)

        extra = models.AccountExtraInfo()
        try:
            extra = models.AccountExtraInfo.objects.get(id=input_array['extra_id'])
            extra.delete()
        except extra.DoesNotExist as e:
            # return response.error('DoesNotExist', f'extra id [{input_array["extra_id"]}] not exist.')
            return response.error('DoesNotExist', 'extra id [{}] not exist.'.format(input_array["extra_id"]))
        except Exception as e:
            return response.error(str(e), "delete extra failed.")
        # return response.ok(f'delete extra info [{input_array["extra_id"]}] success!')
        return response.ok('delete extra info [{}] success!'.format(input_array["extra_id"]))
    else:
        return response.error("PostOnly")
